<?php

namespace app\libs\AsiabillSDK\builder;

use app\constant\ModelConstant;
use app\model\Orders;
use app\trait\OrderTrait;

class RepurchaseBuilder extends BuilderBase
{
    use OrderTrait;
    public function toArray()
    {
        list($products,$subTotal) = $this->getGoodsDetails();
        $orderName = $this->order->name;
        $newOrderNo = $this->formatOrderNo($this->order->shop_id,$orderName);
        $this->repurchaseQuery['order_id'] = $this->order->id;
        list($total_price,$tax_price) = Orders::calculateRepurchase($this->order->total_present);
        return [
                'callbackUrl'=>$this->order->notify_url,
                'customerPaymentMethodId'=>$this->getCustomerPaymentMethodId(),
                'isMobile'=>'0',
                'customerIp'=>self::CUSTOMER_CLIENT_IP,
                'orderAmount'=> $total_price,
                'orderCurrency'=>$this->order->present_currency,
                'platform'=>'php_SDK',
                'remark'=>strval($this->order->id),
                'returnUrl'=>$this->getReturnUrl(),
                'webSite'=>$this->order->shop->website ?: $this->order->shop->host,
                'shipping'=>$this->getShipping(),
                'goodsDetails'=>$products,
                'orderNo'=>$newOrderNo,//订单号
                //'tokenType'=>'RECURRING'
            ];
    }

    public function getGoodsDetails()
    {
        $products = [];
        $subTotal = 0;
        $repurchaseLines = $this->order->items()->select()->toArray();
        foreach ( $repurchaseLines as $items){
            $sub = bcmul($items->price,$items->quantity,2);
            $subTotal = bcadd($subTotal,$sub,2);
            $products[] = [
                'goodsCount' => $items->quantity,
                'goodsPrice' => $items->price,
                'goodsTitle' => $items->title
            ];
        }
        return [$products,$subTotal];
    }
}